package com.zhu.classpath;

import com.zhu.classpath.entry.base.Entry;
import com.zhu.classpath.entry.container.CompositeEntryContainer;

import java.io.File;
import java.io.InputStream;

/**
 * 类路径管理器,管理启动类路径,扩展类路径,用户类路径
 */
public class ClassPathManager {
    //启动类路径管理器
    private  Entry bootClasspath;
    //扩展类路径管理器
    private  Entry extClasspath;
    //用户类路径管理器
    private  Entry userClasspath;

    private ClassPathManager(Entry bootClasspath,Entry extClasspath,Entry userClasspath){
        this.bootClasspath=bootClasspath;
        this.extClasspath=extClasspath;
        this.userClasspath=userClasspath;
    }

    public static ClassPathManager createClassPathManager(String jrePath, String cpPath) {
        //jrePath可以构造出两个东西 一个是启动类路径 一个是扩展类路径
        jrePath=findJreDir(jrePath);
        Entry bootEntryContainer = CompositeEntryContainer.creteCompositeEntryContainer(jrePath + "/lib/*");
        Entry extEntryContainer = CompositeEntryContainer.creteCompositeEntryContainer(jrePath + "/lib/ext/*");
        Entry userEntryContainer = parseUserClasspath(cpPath);
        return new ClassPathManager(bootEntryContainer,extEntryContainer,userEntryContainer);
    }

    private static String findJreDir(String jrePath) {
        //“我想找 JRE 目录，用户给的选项是 jrePath（比如 -Xjre 后面的值）” 优先使用用户指定的。
        if (jrePath != null && new File(jrePath).isDirectory()) {
            return jrePath;
        }
        // 尝试当前目录 “如果当前目录下有个叫 jre 的文件夹，并且它存在，那就用 ./jre”
        //cd /home/user ← 你现在在 /home/user
        //java -cp /my-project/classes MyJvmApp
        //当前目录 = /home/user
        if (new File("./jre").isDirectory()) {
            return "./jre";
        }
        // 尝试 JAVA_HOME
        String javaHome = System.getenv("JAVA_HOME");
        if (javaHome != null) {
            return javaHome + "/jre";
        }
        throw new RuntimeException("Cannot find JRE directory");
    }

    private static Entry parseUserClasspath(String cpPath) {
        if (cpPath == null || cpPath.isEmpty()) {
            return CompositeEntryContainer.creteCompositeEntryContainer("."); // 默认当前目录
        }
        return CompositeEntryContainer.creteCompositeEntryContainer(cpPath);
    }

    public InputStream readClass(String className){
        if (!className.endsWith(".class")) {
            className = className + ".class";
        }
        InputStream bootPathStream = this.bootClasspath.readClass(className);
        if (bootPathStream !=null){
            return bootPathStream;
        }
        InputStream extPathStream = this.extClasspath.readClass(className);
        if (extPathStream !=null){
            return extPathStream;
        }
        InputStream userPathStream = this.userClasspath.readClass(className);
        if (userPathStream !=null){
            return userPathStream;
        }
        return null;
    }
}
